<template>
  <el-container style="height: 100vh; padding: 20px; display: flex; flex-direction: column;">
    <el-row style="flex-grow: 1;">
      <el-col :span="24">
        <el-card class="profile-card" style="height: 100%; display: flex; flex-direction: column;">
          <!-- 用户头像和信息 -->
          <div class="profile-header">
            <!-- 固定头像地址 -->
            <el-avatar src="https://th.bing.com/th/id/R.83933e899522a1c1428bd600ce88ed44?rik=e3F8UnyAmcK46g&pid=ImgRaw&r=0&sres=1&sresct=1" :size="100" class="profile-avatar"></el-avatar>
            <h2>{{ userInfo.username }}</h2>
            <p>{{ userInfo.bio }}</p>
          </div>

          <!-- 用户信息表单 -->
          <div class="profile-details" style="flex-grow: 1; overflow-y: auto;">
            <el-row>
              <el-col :span="12">
                <el-form label-width="120px">
                  <el-form-item label="用户名">
                    <el-input v-model="userInfo.username" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="邮箱">
                    <el-input v-model="userInfo.email" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="个人签名">
                    <el-input
                      type="textarea"
                      v-model="userInfo.bio"
                      disabled
                      :rows="4"
                      placeholder="请输入个人签名"
                    ></el-input>
                  </el-form-item>
                </el-form>
              </el-col>
              <!-- 修改按钮 -->
              <el-col :span="12" class="edit-btn-col">
                <div style="display: flex; justify-content: flex-end; gap: 10px; align-items: center;">
                  <el-button type="primary" @click="openEditDialog" style="background-color: #c1c1c1; border-color: #c1c1c1;">修改信息</el-button>
                  <el-button type="warning" @click="openChangePasswordDialog" style="background-color: #c1c1c1; border-color: #c1c1c1;">修改密码</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 修改信息弹窗 -->
    <el-dialog
      title="修改信息"
      :visible.sync="dialogVisible"
      width="50%"
      @close="resetForm"
    >
      <el-form :model="formData" ref="form" label-width="120px">
        <el-form-item label="用户名" :rules="[{ required: true, message: '请输入用户名', trigger: 'blur' }]">
          <el-input v-model="formData.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="个人签名" :rules="[{ required: true, message: '请输入个人签名', trigger: 'blur' }]">
          <el-input
            type="textarea"
            v-model="formData.bio"
            placeholder="请输入个人签名"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      title="修改密码"
      :visible.sync="passwordDialogVisible"
      width="50%"
      @close="resetPasswordForm"
    >
      <el-form :model="passwordFormData" ref="passwordForm" label-width="120px">
        <el-form-item label="邮箱" :rules="[{ required: true, message: '请输入邮箱', trigger: 'blur' }]">
          <el-input v-model="passwordFormData.email" :disabled="true" placeholder="邮箱" />
        </el-form-item>
        <el-form-item label="当前密码" :rules="[{ required: true, message: '请输入当前密码', trigger: 'blur' }]">
          <el-input
            type="password"
            v-model="passwordFormData.currentPassword"
            placeholder="请输入当前密码"
          />
        </el-form-item>
        <el-form-item label="新密码" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
          <el-input
            type="password"
            v-model="passwordFormData.newPassword"
            placeholder="请输入新密码"
          />
        </el-form-item>
        <el-form-item label="确认新密码" :rules="[{ required: true, message: '请确认新密码', trigger: 'blur' }]">
          <el-input
            type="password"
            v-model="passwordFormData.confirmNewPassword"
            placeholder="确认新密码"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">保存</el-button>
      </span>
    </el-dialog>
  </el-container>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import axios from 'axios';

export default {
  data() {
    return {
      dialogVisible: false, // 控制个人信息弹窗的显示与否
      passwordDialogVisible: false, // 控制修改密码弹窗的显示与否
      formData: {
        username: '',
        bio: '', // 个人签名
      },
      passwordFormData: {
        email: '',  
        currentPassword: '',
        newPassword: '',
        confirmNewPassword: '',
      },
    };
  },
  computed: {
    ...mapState({
      userInfo: state => state.userInfo, // 获取用户信息
      jwtToken: state => state.jwtToken, // 获取 JWT token
    })
  },
  created() {
    this.fetchUserInfo(); // 加载用户信息
  },
  methods: {
    ...mapActions(['fetchUserInfo', 'updateUserInfo']), // 映射 Vuex action

    // 打开修改信息弹窗，填充当前的用户名和个人签名
    openEditDialog() {
      this.formData.username = this.userInfo.username;
      this.formData.bio = this.userInfo.bio; // 填充个人签名
      this.dialogVisible = true; // 显示弹窗
    },

    // 打开修改密码弹窗，填充当前的邮箱
    openChangePasswordDialog() {
      this.passwordFormData.email = this.userInfo.email; // 填充邮箱
      this.passwordDialogVisible = true; // 显示密码修改弹窗
    },

    // 提交修改表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 更新用户名和个人签名
          const updatedInfo = {
            username: this.formData.username,
            bio: this.formData.bio,
          };

          // 调用后端接口保存数据
          this.saveUserInfo(updatedInfo);
        } else {
          console.log('表单验证失败');
        }
      });
    },

    // 向后端发送请求保存用户信息
    saveUserInfo(updatedInfo) {
      const token = sessionStorage.getItem('jwt_token');  // 从 Vuex 获取 JWT token
      axios.put('http://localhost:5000/user/update_userinfo', updatedInfo, {
        headers: {
          'Authorization': `Bearer ${token}`, // 在请求头中带上 JWT token
          'Content-Type': 'application/json',  // 添加 Content-Type
        }
      })
      .then(response => {
        if (response.data.success) {
          this.$message.success('信息已更新');
          this.dialogVisible = false; // 关闭弹窗
          this.fetchUserInfo(); // 重新加载用户信息
        } else {
          this.$message.error('更新失败');
        }
      })
      .catch(error => {
        console.error(error);
        this.$message.error('更新失败');
      });
    },

    // 提交修改密码表单
    submitPasswordForm() {
      // 验证表单
      this.$refs.passwordForm.validate(valid => {
        if (valid) {
          const passwordData = {
            email: this.passwordFormData.email,
            currentPassword: this.passwordFormData.currentPassword,
            newPassword: this.passwordFormData.newPassword,
          };

          this.updatePassword(passwordData);
        } else {
          console.log('密码表单验证失败');
        }
      });
    },

    // 向后端发送请求修改密码
    updatePassword(passwordData) {
      const token = sessionStorage.getItem('jwt_token');  // 从 Vuex 获取 JWT token
      axios.put('http://localhost:5000/user/update_password', passwordData, {
        headers: {
          'Authorization': `Bearer ${token}`, // 在请求头中带上 JWT token
          'Content-Type': 'application/json',  // 添加 Content-Type
        }
      })
      .then(response => {
        if (response.data.message == 'Password updated successfully.') {
          this.$message.success('密码已更新');
          this.passwordDialogVisible = false; // 关闭密码修改弹窗
        } else if(response.data.message == 'Current password and new password are required.'){
          this.$message.error('新密码和旧密码一样');
        }else if(response.data.message == 'Current password is incorrect.'){
          this.$message.error('旧密码不正确');
        }
      })
      .catch(error => {
        console.error(error);
        this.$message.error('密码更新失败');
      });
    },

    // 重置表单
    resetForm() {
      this.$refs.form.resetFields();
    },

    // 重置密码表单
    resetPasswordForm() {
      this.$refs.passwordForm.resetFields();
    }
  }
};
</script>

<style scoped>
.profile-card {
  width: 100%;
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.profile-header {
  text-align: center;
  margin-bottom: 20px;
}

.profile-avatar {
  margin-bottom: 10px;
}

.profile-details {
  padding: 20px;
  background-color: #f4f4f4;
  border-radius: 10px;
  flex-grow: 1;
  overflow-y: auto;
}

.edit-btn-col {
  display: flex;
  justify-content: flex-end; /* 将按钮放置到右侧 */
  align-items: center;
}

.dialog-footer {
  text-align: right;
}

.el-dialog {
  border-radius: 8px;
}
</style>
